﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Pub;
using LZQXT.Test.Forms.DB;

//using Raize.CodeSiteLogging;


namespace LZQXT.Test.Forms
{
    public partial class FDBTree : Form
    {

        const int I_TYPE_ADD = 1;
        const int I_TYPE_DEL = 3;
        const int I_TYPE_EDT = 2;

        public ADOTest ado1 = new ADOTest();
        public ADOTest ado2 = new ADOTest();
        Button[] btnTab;
        CTree ctree = new CTree();
        //int i_gridView_sta = 0;
        //int i_treeNode_sta = 0;
        Label[] lab;
        List<object> lst1 = new List<object>();
        String[] sP_ID;
        String[] sTabData;
        String sTarget = "";
        int Tab_Index = 0;
        TextBox[] tbox;

        public int I_ID = 0;
        public DataSet ds1;
        FDBRow fdbrow;

        public FDBTree()
        {
            InitializeComponent();
        }


        //执行sql语句，显示表格数据
        private void btnTabClick(object sender, EventArgs e)
        {
            Tab_Index = Convert.ToInt32(((Button)sender).Tag);
            if (sTarget.Length == 0)
            {
                dataGridView1.DataSource = null;
                return;
            }

            refGridView();
        }

        private void btn_Click(object sender, EventArgs e)
        {
            int i_btn = 0;

            if (sender is Int32) i_btn = Convert.ToInt32(sender);
            if (sender is MenuItem) i_btn = Convert.ToInt32(((MenuItem)sender).Tag);
            if (sender is ToolStripMenuItem) i_btn = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
            if (sender is Button) i_btn = Convert.ToInt32(((Button)sender).Tag);
            if (sender is ToolStripButton) i_btn = Convert.ToInt32(((ToolStripButton)sender).Tag);

            switch (i_btn)
            {
                case 1:     //fill TreeView
                    //treeView1.Nodes.Clear();


                    if (treeView1.SelectedNode != null)
                    {
                        treeView1.SelectedNode.Nodes.Clear();
                        ctree.fillTreeView(treeView1, treeView1.SelectedNode);
                    }
                    else
                    {
                        treeView1.Nodes.Clear();
                        ctree.fillTreeView(treeView1, null);
                    }

                    break;

                case 10:        //add node
                    if (CPub.MsgBox("确定要添加新的数据到数据库吗？", "添加"))
                    {
                        for (int i = 0; i < ado1.ds.Tables[0].Rows.Count; i++)
                        {
                            if (tbox[0].Text == ado1.ds.Tables[0].Rows[i][0].ToString())
                            {
                                CPub.MsgBox("编号已'" + tbox[0].Text + "'存在");
                                return;
                            }
                        }
                        DataRow dr = ado1.ds.Tables[0].NewRow();
                        for (int i = 0; i < tbox.Length; i++)
                        {
                            dr[i] = tbox[i].Text;
                        }
                        ado1.ds.Tables[0].Rows.Add(dr);
                        ado1.update(ADOTest.I_ADD);
                    }
                    break;
                case 11:        //edit node
                    if (CPub.MsgBox("确定要写入到数据库吗？", "修改"))
                    {
                        for (int i = 0; i < tbox.Length; i++)
                        {
                            ado1.ds.Tables[0].Rows[0][i] = tbox[i].Text;
                        }
                        ado1.update(ADOTest.I_EDT);
                    }
                    break;
                case 12:       //delete node
                    if (CPub.MsgBox("确定要写入到数据库吗？", "删除"))
                    {
                        ado1.ds.Tables[0].Rows[0].Delete();
                        ado1.update(ADOTest.I_DEL);
                    }
                    break;
                case 13:        //refresh node
                    btn_Click(1, null);
                    break;
                case 20:    //add node
                    if (CPub.MsgBox("确定要写入到数据库吗？", "添加"))
                    {
                        if (dataGridView1.Rows.Count > 0)
                        {
                            int i = ado2.ds_count;
                            DataRow dr = ado2.ds.Tables[0].NewRow();
                            for (int j = 0; j < ado2.ds.Tables[0].Columns.Count; j++)
                            {
                                dr[j] = dataGridView1.Rows[i].Cells[j].Value;
                            }
                            ado2.ds.Tables[0].Rows.Add(dr);
                            ado2.update(ADOTest.I_ADD);
                        }
                    }
                    break;
                case 21:    //edit node
                    if (CPub.MsgBox("确定要写入到数据库吗？", "修改"))
                    {
                        if (dataGridView1.Rows.Count > 0)
                        {
                            for (int i = 0; i < ado2.ds.Tables[0].Rows.Count; i++)
                            {
                                for (int j = 0; j < ado2.ds.Tables[0].Columns.Count; j++)
                                {
                                    ado2.ds.Tables[0].Rows[i][j] = dataGridView1.Rows[i].Cells[j].Value;
                                }
                            }
                            ado2.update(ADOTest.I_EDT);
                        }
                    }
                    break;
                case 22:    //delete node
                    if (CPub.MsgBox("确定要写入到数据库吗？", "删除"))
                    {
                        if (dataGridView1.SelectedRows.Count > 0)
                        {
                            int r_Count = dataGridView1.SelectedRows.Count;
                            for (int i = 0; i < r_Count; i++)
                            {
                                ado2.ds.Tables[0].Rows[dataGridView1.SelectedRows[0].Index].Delete();
                            }
                            ado2.update(ADOTest.I_DEL);
                        }
                    }
                    break;
                case 23:    //refresh node
                    treeView1_AfterSelect(treeView1, null);
                    break;
                case 24:    //creat table
                    CCreateGrid.creatTab(sTarget);
                    break;
                case 25:    //creat table
                    CCreateGrid.creatDetailTab(sTarget);
                    break;
                case 26:    //delete table
                    CCreateGrid.deleteTab(sTarget);
                    break;
                case 27:    //delete table
                    CCreateGrid.deleteDetailTab(sTarget);
                    break;

                case 31:    //add ado
                    FDBLogin fdblogin = new FDBLogin();
                    fdblogin.ShowDialog();
                    ado2.S_Con = ado1.S_Con;
                    btn_Click(1, null);
                    break;
                case 32:    //close ado
                    treeView1.Nodes.Clear();
                    break;
                case 33:    //refresh ado
                    btn_Click(1, null);
                    break;
            }
        }

        private void FGSMA_P_Class_Load(object sender, EventArgs e)
        {
            treeView1.Dock = DockStyle.Fill;
            dataGridView1.Dock = DockStyle.Fill;
            tabControl1.Dock = DockStyle.Fill;
            tboxBtnSQL.Dock = DockStyle.Fill;
            tabControl1.SelectedIndex = 0;

            Program.fsta_id.TopLevel = false;
            Program.fsta_id.Parent = tabPage3;
            Program.fsta_id.FormBorderStyle = FormBorderStyle.None;
            Program.fsta_id.Dock = DockStyle.Fill;
            Program.fsta_id.Show();

            Program.fdefval.TopLevel = false;
            Program.fdefval.Parent = tabPage4;
            Program.fdefval.FormBorderStyle = FormBorderStyle.None;
            Program.fdefval.Dock = DockStyle.Fill;
            Program.fdefval.Show();

            Program.ftemtest.TopLevel = false;
            Program.ftemtest.Parent = tabPage5;
            Program.ftemtest.FormBorderStyle = FormBorderStyle.None;
            Program.ftemtest.Dock = DockStyle.Fill;
            Program.ftemtest.Show();

            Program.foptrain.TopLevel = false;
            Program.foptrain.Parent = tabPage6;
            Program.foptrain.FormBorderStyle = FormBorderStyle.None;
            Program.foptrain.Dock = DockStyle.Fill;
            Program.foptrain.Show();

            //CGridViewMenu gridMenu = new CGridViewMenu(dataGridView1, ado1);

            sTabData = ConfigurationManager.AppSettings["TabDataName"].Split(';');
            sP_ID = ConfigurationManager.AppSettings["TabDataID"].Split(';');

            ctree.sTabName = ConfigurationManager.AppSettings["sTabName"];
            ctree.sPreCol = ConfigurationManager.AppSettings["sPreCol"];
            ctree.sIDCol = ConfigurationManager.AppSettings["sIDCol"];
            ctree.sName = ConfigurationManager.AppSettings["sName"];
            ctree.sTagID = ConfigurationManager.AppSettings["sTagID"];
            ctree.sOrderID = ConfigurationManager.AppSettings["sOrderID"];
            //ctree.fillTreeView(treeView1, null);
            //panel2.Dock = DockStyle.Fill;

            int btn_left = 5;
            int btn_top = 5;
            btnTab = new Button[sTabData.Length];
            for (int i = 0; i < sTabData.Length; i++)
            {
                btnTab[i] = new Button();
                btnTab[i].Text = sTabData[i];
                btnTab[i].Tag = i;
                btnTab[i].Width = 150;
                btnTab[i].Height = 25;
                btnTab[i].Top = btn_top;
                btnTab[i].Left = btn_left;
                btnTab[i].Parent = panel5;
                btnTab[i].Click += btnTabClick;

                btn_left += 160;
                if (btn_left > panel5.Width)
                {
                    btn_left = 5;
                    btn_top += 30;
                    panel5.Height += 30;
                }
            }

            panelNode.Dock = DockStyle.Fill;
            fdbrow = new FDBRow();
            fdbrow.TopLevel = false;
            fdbrow.Parent = panelNode;
            fdbrow.FormBorderStyle = FormBorderStyle.None;
            fdbrow.Dock = DockStyle.Fill;
            fdbrow.Show();

        }

        private void openDir()
        {
            string sID = Convert.ToString(treeView1.SelectedNode.Tag);
            ADOTest ado1 = new ADOTest();
            DataSet ds1 = ado1.sel1("select * from GSMA_P_Class where id=" + sID);
            if (!CPub.dsIsNull(ds1))
            {
                string sPath = CPub.webPath + ds1.Tables[0].Rows[0]["path"].ToString();
                CPub.Send(sPath);
                CPub.runExe("Explorer.exe", sPath.Replace(@"/", @"\"));
            }
        }

        //填充gridView
        private void refGridView()
        {
            dataGridView1.DataSource = null;

            String strSQL2 = sP_ID[Tab_Index].Replace("{0}", sTarget);
            tboxBtnSQL.Text = strSQL2;
            CDebug.Send(strSQL2);


            try
            {
                DataSet ds2 = ado2.sel1(strSQL2);
                dataGridView1.DataSource = ds2.Tables[0];
            }
            catch (System.Exception ex)
            {
                dataGridView1.DataSource = null;
                CDebug.SendError(ex.ToString());
            }

        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                if (btnTab != null && btnTab.Length > 0 && panel5.Width > btnTab[0].Width)
                {
                    int btn_left = 5;
                    int btn_top = 5;
                    panel5.Height = 35;

                    for (int i = 0; i < btnTab.Length; i++)
                    {
                        if (btn_left + btnTab[i].Width > panel5.Width)
                        {
                            btn_left = 5;
                            btn_top += 30;
                            panel5.Height = btn_top + 30;
                        }

                        btnTab[i].Top = btn_top;
                        btnTab[i].Left = btn_left;

                        btn_left += 160;
                    }
                }
            }
        }

        public void showFieldWindow()
        {
            if (ds1.Tables.Count > 0)
            {
                fdbrow.ado1 = ado1;
                fdbrow.sTabName = ctree.sTabName;
                fdbrow.ds1 = ds1;
                fdbrow.i_RowIndex = 0;
                fdbrow.field_Ref();
                fdbrow.Show();
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            CDebug.EnterMethod("点击树列表，加载数据");
            try
            {
                treeView1.SelectedNode.SelectedImageIndex = treeView1.SelectedNode.ImageIndex;
                foreach (object obj1 in lst1)
                {
                    if (obj1 is Label) ((Label)obj1).Dispose();
                    if (obj1 is Button) ((Button)obj1).Dispose();
                    if (obj1 is TextBox) ((TextBox)obj1).Dispose();
                }

                string sID = Convert.ToString(treeView1.SelectedNode.Tag);

                sTarget = ((LZQXT.Test.TreeNodeII)treeView1.SelectedNode).Target;

                if (sTarget != string.Empty)
                {
                    I_ID = Convert.ToInt32(sTarget);
                    Program.fsta_id.showDB();
                }

                for (int i = 0; i < btnTab.Length; i++)
                {
                    if (sTarget != "")
                    {
                        btnTab[i].Text = sTabData[i].Replace("{ID}", sTarget);
                    }
                    else
                    {
                        btnTab[i].Text = sTabData[i];
                    }
                }

                ds1 = ado1.sel1("select * from " + ctree.sTabName + " where " + ctree.sIDCol + "=" + sID);
                showFieldWindow();

                /*
                #region 动态生成按钮和输入框

                panel2.Visible = false;

                //创建文本框
                int i_X = 0;
                int i_Y = 0;
                int i_h = 0;

                //动态生成文本框
                if (!CPub.dsIsNull(ds1))
                {

                    DataRow dr = ds1.Tables[0].Rows[0];
                    lab = new Label[dr.ItemArray.Length];
                    tbox = new TextBox[dr.ItemArray.Length];
                    DataColumnCollection dc = ds1.Tables[0].Columns;
                    for (int i = 0; i < dr.ItemArray.Length; i++)
                    {
                        i_Y = 25 * i_h + 30;
                        if (i_Y + 30 > panel2.Height)
                        {
                            i_h = 0;
                            i_Y = 25 * i_h + 30;
                            i_X = 450;
                        }
                        i_h++;

                        lab[i] = new Label();
                        lab[i].Text = dc[i].Caption;
                        lab[i].Left = 30 + i_X;
                        lab[i].Top = i_Y;
                        lab[i].Parent = panel2;
                        lst1.Add(lab[i]);

                        tbox[i] = new TextBox();
                        tbox[i].Text = dr[i].ToString();
                        tbox[i].Left = 150 + i_X;
                        tbox[i].Top = i_Y;
                        tbox[i].Width = 300;
                        tbox[i].Parent = panel2;
                        lst1.Add(tbox[i]);
                    }
                }

                //动态生成按钮
                string[] sCap = new string[] { "add", "edit", "delete", "refresh" };
                for (int i = 0; i < 4; i++)
                {
                    Button btn = new Button();
                    btn.Tag = 10 + i;
                    btn.Top = 10;
                    btn.Left = i * 100 + 50;
                    btn.Width = 80;
                    btn.Text = sCap[i];
                    btn.Parent = panel4;
                    btn.Click += btn_Click;
                    lst1.Add(btn);
                }

                panel2.Visible = true;

                #endregion
                */

                //DataSet ds2 = gsma_p_data.GetList("ClassID=" + sID);
                if (sTarget != "")
                {
                    refGridView();
                }
                else
                {
                    dataGridView1.DataSource = null;
                }

                string[] sCap2 = new string[] { "add", "edit", "delete", "refresh", "creatTab", "creatDetailTab", "delTab", "delDetailTab" };
                for (int i = 0; i < sCap2.Length; i++)
                {
                    Button btn = new Button();
                    btn.Tag = 20 + i;
                    btn.Top = 5;
                    btn.Left = i * 100 + 50;
                    btn.Width = 80;
                    btn.Text = sCap2[i];
                    btn.Parent = panel3;
                    btn.Click += btn_Click;
                    lst1.Add(btn);
                }

                try
                {
                    Program.fdefval.s_ID = sTarget;
                    Program.fdefval.init();
                }
                catch (System.Exception ex)
                {
                    CDebug.SendError(ex.ToString());
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
            CDebug.ExitMethod("点击树列表，加载数据");
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (CDB.dsIsNull(ado2.ds)) return;

                int i_r = e.RowIndex;
                CDebug.Send("" + i_r);

                if (ado2.ds.Tables[0].Columns[1].Caption != "Title") return;

                if (ado2.ds.Tables[0].Rows[i_r]["Title"].ToString() == "站号" || ado2.ds.Tables[0].Rows[i_r]["Title"].ToString() == "站点")
                {
                    Program.fsta_id.tboxStaID.Text = ado2.ds.Tables[0].Rows[i_r]["Val"].ToString();

                    //if (ado2.ds.Tables[0].Rows[i_r + 1]["Title"].ToString() == "站点")
                    Program.fsta_id.tboxStaName.Text = ado2.ds.Tables[0].Rows[i_r + 1]["Val"].ToString();
                }

            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
                CDebug.Send("核对站号：", ex);
                MessageBox.Show(ex.ToString());
            }
        }
    }
}